import comTitle from "@/views/com/com_title.vue";
import cropperModal from "@/components/cropper/index.vue";
import QuillEditor from "@/components/Editor/QuillEditor.vue";
import { fileBase64, toDecimal2, toDecimal3 } from '@/util/util'
import { addObj, putObj, platformgoodscategorytree, goodstockfetchList, goodstockfetchListAll, goodstype, getTpyeId, merchantinfofetchList, getPlatformShopInfo, platformgoodsinfodetail } from '@/api/shop/goods/list.js'
import { upLoad } from '@/api/shop/upLoad.js'
import store from "@/store";
export default {
    components: {
        comTitle,
        cropperModal,
        QuillEditor
    },
    data() {
        return {
            headers: {
                Authorization: "Bearer " + store.getters.access_token,
            },
            labelWidth: "150px",
            disabled: false,
            ruleForm: {
                sptm: 0,
                saleScope: '00',
                service: [],
                pid: [],
                shopId: [],
                isshopGoods: '01',
                supplierMerchants: [],
                costPrice: '0.00',
                promotePrice: '0.00',
                sellingPrice: '0.00',
                detailList: []
            },

            soldOut: true,  //如初始库存为0，商品上架后为售罄状态
            rules: {
                goodsName: [
                    { required: true, message: '请输入商品名称，不超过30个字符', trigger: 'blur' },
                ],
                sptm: [
                    { required: true, message: '请选择是否是商品条码', trigger: 'change' },
                ],
                pid: [
                    { required: true, message: '请选择商品类目', trigger: 'blur' },
                ],
                barCode: [
                    { required: true, message: '请输入商品条码', trigger: 'blur' },
                ],
                typeId: [
                    { required: true, message: '请选择商品类型', trigger: 'change' },
                ],
                goodsDes: [
                    { required: true, message: '请输入商品描述', trigger: 'blur' },
                ],
                saleScope: [
                    { required: true, message: '请选择销售渠道', trigger: 'change' },
                ],
                serviceDuration: [
                    { required: true, message: '请选择服务时长', trigger: 'change' },
                ],
                service: [
                    { required: true, message: '请选择服务时段', trigger: 'change' },
                ],
                shopId: [
                    { required: true, message: '请选择指定门店', trigger: 'change' },
                ],
                isshopGoods: [
                    { required: true, message: '请选择是否门店商品', trigger: 'change' },
                ],
                stockUnit: [
                    { required: true, message: '请选择库存单位', trigger: 'change' },
                ],
                stockNum: [
                    { required: true, message: '请输入库存数量', trigger: 'blur' },
                ],
                typeId: [
                    { required: true, message: '请选择商品类型', trigger: 'change' },
                ],
                convertUnit: [
                    { required: true, message: '请选择库存换算单位', trigger: 'change' },
                ],
                convertUnitNum: [
                    { required: true, message: '请输入库存换算数量', trigger: 'blur' },
                ],
                sellingPrice: [
                    { required: true, message: '请输入销售价', trigger: 'blur' },
                ],
                costPrice: [
                    { required: true, message: '请输入成本', trigger: 'blur' },
                ],
                promotePrice: [
                    { required: true, message: '请输入促销价', trigger: 'blur' },
                ],
            },
            supplierMerchantIdList: [],//供应商名称
            categoryIdList: [], //商品类目
            typeIdList: [], //商品类型
            typeIdAttribute: [],
            stockUnitList: [],//库存单位
            serviceDurationList: [  //服务时长
                // {
                //     label: "0",
                //     value: "00"
                // },
                {
                    label: "1",
                    value: "01"
                }, {
                    label: "2",
                    value: "02"
                }, {
                    label: "3",
                    value: "03"
                }, {
                    label: "4",
                    value: "04"
                }, {
                    label: "5",
                    value: "05"
                }, {
                    label: "6",
                    value: "06"
                }
            ],
            serviceTimesList: [],  //服务时段

            mendianList: [  //门店list

            ],

            sptmPlaceholder: false,  //商品条码
            imageUrl: "",
            loading: false,  //上传
            optionsData: {
                title: "商品图片",     //弹框表头
                img: '',   //裁切图片地址
                autoCrop: true, //是否默认生成截图框
                autoCropWidth: 200, //默认生成截图框宽度
                autoCropHeight: 200, //默认生成截图框高度
                fixedBox: false, //固定截图框大小 不允许改变
                thumbnailName: "衣家生活"
            },
            number: 0,
            fileList: [],
            dialogImageUrl: '',  //放大图片
            dialogVisible: false,
            danwei: 1,

            timer: null, //时长计算
            timeNum: 0,
            imgUrlList: [],
            loadingSure: false,

            uploading: true
        }
    },
    created() {
        this.getList()
        this.getPlatformgoodscategorytree({})
    },
    mounted() {
        if (this.$route.query.id) {
            this.getObjData(this.$route.query.id)
        }
    },
    // 最后在beforeDestroy()生命周期内清除定时器：
    beforeDestroy() {
        clearInterval(this.timer);
        this.timer = null;
    },
    updated() {
        if (this.timeNum == this.serviceTimesList.length) {
            this.clearTimer()
        }
    },
    watch: {
        yingYeTimes(val) {
            console.log(val)
            if (val.length == 17) {
                console.log('clearInterval')
                clearInterval(this.timer)
            }
        }
    },
    methods: {
        getList() {
            // goodstockfetchList().then(val => {  //库存单位
            //     let data = val.data.data
            //     console.log('库存单位', data)
            //     this.stockUnitList = data.records.map(item => {
            //         return {
            //             value: item.stockUnitId + '',
            //             label: item.stockUnitName
            //         }
            //     })
            // })

            goodstockfetchListAll().then(val => {  //库存单位
                let data = val.data.data
                console.log('库存单位', data)
                this.stockUnitList = data.map(item => {
                    return {
                        value: item.stockUnitId + '',
                        label: item.stockUnitName
                    }
                })
            })

            goodstype().then(val => {  //商品类型
                let data = val.data.data
                console.log('商品类型', data)
                this.typeIdList = data.records.map(item => {
                    return {
                        value: item.typeId,
                        label: item.typeName,
                        goodsAttributeName: item.goodsAttributeName
                    }
                })
            })
            merchantinfofetchList({ businessType: this.$route.query.businessType }).then(val => {  //供应商
                let data = val.data.data
                console.log('供应商', data)
                this.supplierMerchantIdList = data.map(item => {
                    return {
                        value: item.merchantId,
                        label: item.companyName,
                    }
                })
            })
            getPlatformShopInfo({ businessType: this.$route.query.businessType }).then(val => {  //获取平台下门店
                let data = val.data.data


                if (!this.$route.query.id) {
                    this.ruleForm.shopId = data.map(item => {
                        return item.shopId
                    })
                }


                this.mendianList = data.map(item => {
                    return {
                        value: item.shopId,
                        label: item.shopName + ((item.provinceCode && item.provinceCode && item.districtCode) ? '-' : '') + (item.provinceCode ? item.provinceCode : '') + (item.cityCode ? item.cityCode : '') + (item.districtCode ? item.districtCode : ''),
                    }
                })

                console.log('this.ruleForm.shopId', this.ruleForm.shopId)
            })
        },
        getPlatformgoodscategorytree(obj) {
            platformgoodscategorytree(Object.assign({ businessType: this.$route.query.businessType }, obj)).then(val => {  //商品类目
                let data = val.data.data
                console.log('商品类目', data)
                this.categoryIdList = data.map(item => {
                    return {
                        value: item.categoryId,
                        label: item.categoryName,
                        children: item.children.map(items => {
                            return {
                                value: items.categoryId,
                                label: items.categoryName,
                            }
                        })
                    }
                })
            })
        },
        submitSave() {   //提交并保存
            console.log(this.ruleForm)
            this.$refs['ruleForm'].validate((valid) => {
                if (valid) {
                    if (this.ruleForm.sptm == 0) {
                        this.rules.sptm[0].required = false;  //商品条码
                    } else {
                        this.rules.sptm[0].required = true;
                    }
                    if (this.ruleForm.pid) {
                        if (this.ruleForm.pid.length > 1) {  //商品类目
                            this.ruleForm.categoryId = this.ruleForm.pid[1]
                        } else {
                            this.ruleForm.categoryId = this.ruleForm.pid[0]
                        }
                    }

                    if (this.$route.query.businessType == '04') {  //服务时长
                        if (this.ruleForm.service.length > 0) {
                            let servicelist = [...this.ruleForm.service]
                            this.ruleForm.serviceTimes = servicelist.join(',')
                        } else {
                            this.$message.warning('请选择服务时间段')
                            return
                        }

                    }

                    let urlList = [...this.imgUrlList]
                    if (urlList.length) {  //图片处理
                        let imgList = []
                        urlList.forEach(item => {
                            if (item.url.indexOf(process.url) > -1) {  //截取路径
                                item.url = item.url.replace(process.url, '')
                            }
                            imgList.push(item.url)
                        })
                        this.ruleForm.goodsPic = imgList.join(',')
                    }


                    this.ruleForm.businessType = this.$route.query.businessType
                    if (this.ruleForm.shopId) {
                        if (this.ruleForm.shopId.length) {
                            this.ruleForm.distributionChannel = this.ruleForm.shopId.join(',')
                        }
                    }

                    if (this.ruleForm.supplierMerchants) {   //供应商
                        if (this.ruleForm.supplierMerchants.length) {   //供应商
                            this.ruleForm.supplierMerchantIds = this.ruleForm.supplierMerchants.join(',')
                        }
                    }

                    console.log(this.ruleForm)
                    if (this.ruleForm.goodsPic) {
                        this.loadingSure = true
                        if (this.$route.query.id) {
                            // if (this.ruleForm.detailList.some(item => {
                            //     return item.valueList.length > 0
                            // })) {

                            // } else {
                            //     this.$message.warning('请选择商品类型关联出的属性')
                            // }
                            putObj(this.ruleForm).then(val => {
                                this.$message.success('修改成功')
                                this.quxiao('ruleForm')
                            }).catch(() => {
                                this.loadingSure = false
                            })
                        } else {
                            // if (this.ruleForm.detailList.some(item => {
                            //     return item.valueList.length > 0
                            // })) {

                            // } else {
                            //     this.$message.warning('请选择商品类型关联出的属性')
                            // }
                            addObj(this.ruleForm).then(val => {
                                this.$message.success('添加成功')
                                this.quxiao('ruleForm')
                            }).catch(() => {
                                this.loadingSure = false
                            })
                        }
                    } else {
                        this.$message.warning('请上传商品图片')
                    }

                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        sptmChange(e) {
            console.log(this.ruleForm)
            if (e == 0) {
                this.ruleForm = {
                    sptm: 0,
                    saleScope: '00',
                }
            }
        },
        quxiao(ruleForm) {  //取消
            this.$router.go(-1)
            this.$refs[ruleForm].resetFields();
            this.ruleForm = {
                sptm: 0,
                saleScope: '00',
                service: [],
                pid: [],
                shopId: []
            }
            this.loadingSure = false
        },
        // supplierMerchantIdsChange(e) {  //供应商关联类目

        //     let list = [...e]
        //     console.log(list)
        //     var a = list.join(',')
        //     this.getPlatformgoodscategorytree({ supplierMerchantId: a })
        // },
        setMaster(file) {  //设置主图
            let subFile = this.imgUrlList[this.fileList.indexOf(file)]  //找到提交的图片数组

            for (var i = 0; i < this.fileList.length; i++) {  //根据file 找到数组的位置
                if (this.fileList[i] === file) {
                    this.fileList.splice(i, 1);
                    this.imgUrlList.splice(i, 1);
                    break;
                }
            }
            this.imgUrlList.unshift(subFile);  //提交的图片
            this.fileList.unshift(file);  //回显的图片
            console.log(this.imgUrlList)
            console.log(this.fileList)
        },
        handleChange(file) {  //上传触发
            // console.log(file)
            let { options } = this;
            // console.log(file)
            // fileBase64(file.file.originFileObj).then(result => {
            let target = Object.assign({}, options, {
                img: file.url,
                files: file
            })
            this.$refs['cropperModal'].edit(target);
            // })
        },
        beforeUpload(file) {
            const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
            if (!isJpgOrPng) {
                this.$message.error('图片格式不支持！');
            }
            const isLt10M = file.size / 1024 / 1024 < 10;
            if (!isLt10M) {
                this.$message.error('图片大小限制在10MB内!');
            }
            return isJpgOrPng && isLt10M;
        },
        handlePictureCardPreview(file) {
            this.dialogVisible = true,
                this.dialogImageUrl = file.url
        },
        delUplod(file) {
            const index = this.fileList.indexOf(file)
            const newFileList = this.fileList.slice()
            newFileList.splice(index, 1)
            this.fileList = newFileList
            this.imgUrlList.splice(index, 1)
        },
        handleCropperSuccess(data) {  //图片裁切完成保存
            console.log(data)
            upLoad(data).then(res => {
                this.imgUrlList.push(res.data.data)
                this.fileList.push({
                    uid: this.number++,
                    name: 'image.png',
                    status: 'done',
                    url: URL.createObjectURL(data)
                })
                this.$message.success('上传成功！')
            }).catch(() => {
                this.$message.warning('上传失败，请重新上传！')
            })
        },
        handleGoodsPicUploadSuccess(res, file, fileList) {
            console.log('handleGoodsPicUploadSuccess', res)
            this.imgUrlList.push({
                uid: this.number++,
                name: res.data.fileName,
                status: 'done',
                url: res.data.url
            });
            // this.fileList.push({
            //     uid: this.number++,
            //     name: res.data.fileName,
            //     status: 'done',
            //     url: res.data.url
            // })
            this.fileList = fileList
            if (this.fileList.some(item => { return item.status == "uploading" })) { //检测是否存在正在上传的图片，若有 不允许有任何操作
                this.uploading = false
            } else {
                this.uploading = true
            }


            console.log('handleGoodsPicUploadSuccess this.imgUrlList', this.imgUrlList)
            console.log('handleGoodsPicUploadSuccess this.fileList', this.fileList)
            this.$message.success('上传成功！')
        },
        onProgress(event, file, fileList) {
            this.uploading = false
        },
        onExceed(files, fileList) { //上传文件限制函数
            if (!fileList.length < 7) {
                this.$message.error('最多上传6张图!');
            }
        },
        toDecimalBlur(name) {  //保留两位小数
            let value = ''
            if (name === 'xsj') {
                if (this.ruleForm.sellingPrice) {
                    value = this.ruleForm.sellingPrice.replace(/[\u4e00-\u9fa5]/g, '')
                    this.ruleForm.sellingPrice = toDecimal2(Number(value))
                    this.getGrossProfit()
                } else {
                    this.ruleForm.sellingPrice = '0.00'
                    this.getGrossProfit()
                }

            } else if (name === 'cbj') {
                if (this.ruleForm.costPrice) {
                    value = this.ruleForm.costPrice.replace(/[\u4e00-\u9fa5]/g, '')
                    this.ruleForm.costPrice = toDecimal2(Number(value))
                    this.getGrossProfit()
                } else {
                    this.ruleForm.costPrice = '0.00'
                    this.getGrossProfit()
                }

            } else if (name === 'cxj') {
                if (this.ruleForm.promotePrice) {
                    value = this.ruleForm.promotePrice.replace(/[\u4e00-\u9fa5]/g, '')
                    this.ruleForm.promotePrice = toDecimal2(Number(value))
                    this.getGrossProfit()
                } else {
                    this.ruleForm.promotePrice = '0.00'
                    this.getGrossProfit()
                }
            } else if (name === 'kcsl') {
                if (this.ruleForm.stockNum) {
                    value = this.ruleForm.stockNum.replace(/[\u4e00-\u9fa5]/g, '')
                    this.ruleForm.stockNum = toDecimal3(Number(value))
                }
            }

        },
        getGrossProfit() {  //获取毛利
            this.ruleForm.grossProfit = ''
            console.log(this.ruleForm.promotePrice)
            if (this.ruleForm.promotePrice != '0.00') {
                this.ruleForm.grossProfit = (this.ruleForm.promotePrice - this.ruleForm.costPrice).toFixed(2)
                this.getGrossProfitRate()
            } else {
                this.ruleForm.grossProfit = (this.ruleForm.sellingPrice - this.ruleForm.costPrice).toFixed(2)
                this.getGrossProfitRate()
            }

        },
        getGrossProfitRate() {//获取毛利率
            this.ruleForm.grossProfitRate = ''
            var rate = 0
            if (this.ruleForm.promotePrice != '0.00') {
                rate = parseFloat(this.ruleForm.grossProfit) / parseFloat(this.ruleForm.promotePrice)
                this.ruleForm.grossProfitRate = rate.toFixed(4)

            } else {
                rate = parseFloat(this.ruleForm.grossProfit) / parseFloat(this.ruleForm.sellingPrice)
                this.ruleForm.grossProfitRate = rate.toFixed(4)
            }
            this.ruleForm.grossProfitRate = (this.ruleForm.grossProfitRate * 100).toFixed(2)
        },

        addKchs() {    //库存换算新增
            this.ruleForm.kchs.push({});
        },
        editKchs(item) {  //库存换算删除
            let index = this.ruleForm.kchs.indexOf(item);
            if (index !== -1) {
                this.ruleForm.kchs.splice(index, 1);
            }
        },
        cxsjChange(e) {  //促销时间
            this.ruleForm.startCxsj = e[0]
            this.ruleForm.endCxsj = e[1]
        },
        editorChange(quill, html, text) {  //富文本编辑器
            console.log(quill)
            console.log(html)
            console.log(text)
            this.ruleForm.goodsDetails = html
            console.log(this.ruleForm.goodsDetails)
        },

        getObjData(id) {  //编辑回显
            platformgoodsinfodetail(id).then(val => {
                console.log(val)
                let data = val.data.data
                this.ruleForm = data
                this.ruleForm.stockNum = this.ruleForm.goodsStockNum
                if (this.ruleForm.distributionChannel) {
                    if (this.ruleForm.distributionChannel.length) {
                        this.ruleForm.shopId = this.ruleForm.distributionChannel.split(',')
                    }
                }

                if (this.ruleForm.barCode) {
                    this.ruleForm.sptm = 1
                } else {
                    this.ruleForm.sptm = 0
                }

                if (this.ruleForm.categoryId) {
                    let pid = []
                    pid.push(this.ruleForm.categoryId)
                    if (this.ruleForm.pid != '0') {  //pid 父级id
                        pid.unshift(this.ruleForm.pid)
                    }
                    this.ruleForm.pid = pid
                    console.log('pid', this.ruleForm.pid)
                    this.typeIdChange(this.ruleForm.typeId)  //商品属性
                }

                let pic = []            //图片回显
                if (this.ruleForm.goodsPic) {
                    if (this.ruleForm.goodsPic.indexOf(',') > -1) {
                        pic = this.ruleForm.goodsPic.split(',')
                        pic.forEach(item => {
                            this.fileList.push({ url: item, name: '商品图片' })
                            this.imgUrlList.push({ url: item, name: '商品图片' })
                        })
                    } else {
                        this.fileList.push({ url: this.ruleForm.goodsPic, name: '商品图片' })
                        this.imgUrlList.push({ url: this.ruleForm.goodsPic, name: '商品图片' })
                    }
                }


                if (this.$route.query.businessType == '04') { //服务时长
                    if (this.ruleForm.serviceDuration) {
                        this.serviceDurationChange(this.ruleForm.serviceDuration)
                        if (this.ruleForm.serviceTimes) {
                            this.ruleForm.service = this.ruleForm.serviceTimes.split(',')
                            this.ruleForm.service = [...this.ruleForm.service]
                        }

                    }
                }

                if (this.ruleForm.suplierInfoList) {   //供应商
                    if (this.ruleForm.suplierInfoList.length) {   //供应商
                        this.ruleForm.supplierMerchants = this.ruleForm.suplierInfoList.map(item => {
                            return item.suplierMerchantId
                        })
                    }
                }


                console.log('ruleFormruleFormruleForm', this.ruleForm)
            })
        },

        typeIdChange(val) {  //商品类型关联出属性
            getTpyeId(val).then(val => {
                let data = val.data.data
                console.log(data)
                this.typeIdAttribute = data.map(item => {
                    return {
                        goodsAttributeName: item.goodsAttributeName,
                        goodsAttributeValues: item.goodsAttributeValue.split(','),
                        goodsAttributeId: item.goodsAttributeId,
                    }
                })
                this.typeIdAttribute = this.typeIdAttribute.map(item => {
                    return {
                        goodsAttributeName: item.goodsAttributeName,
                        goodsAttributeId: item.goodsAttributeId,
                        valueList: [],
                        goodsAttributeValues: item.goodsAttributeValues.map(items => {
                            return {
                                label: items,
                                value: items,
                            }
                        })
                    }
                })

                if (this.$route.query.id) {
                    this.typeIdAttribute.forEach(item => {  //编辑类型属性回显
                        this.ruleForm.goodAttribute.forEach(item1 => {
                            item1.goodAttributeValue.forEach(item2 => {
                                if (item1.goodsAttributeId == item.goodsAttributeId) {
                                    item.valueList.push(item2.goodsAttributeValue)
                                }
                            })
                        })
                    })
                }
                this.ruleForm.detailList = this.typeIdAttribute
            })
        },
        changeHandler() { //商品属性
            this.ruleForm.detailList = this.typeIdAttribute.map(item => {
                return {
                    goodsAttributeId: item.goodsAttributeId,
                    valueList: item.valueList
                }
            })
        },

        isshopGoodsChange(e) {  //指定门店
            // if (e == '00') {
            //     let list = []
            //     this.mendianList.forEach(item => {
            //         list.push(item.value)
            //     })
            //     this.ruleForm.distributionChannel = list.join(',')
            // }
        },
        serviceDurationChange(e) {  //服务时段
            let y = 6, z = 0, k = parseInt(e)   //y起始时间  z前面的字段值 k共有多少个可能
            this.timeNum = parseInt(16 / e)
            this.ruleForm.service = []
            this.serviceTimesList = []
            this.timer = setInterval(() => {
                z = y
                y += k
                this.serviceTimesList.push({ label: z + ':00 ' + '-' + y + ':00', value: z + ':00 ' + '-' + y + ':00' })
            }, 0)
        },
        // serviceChange(e) {
        //     console.log(e)
        //     e.forEach(item => {
        //         this.serviceTimesList.forEach(items => {
        //             if (item == '全部') {
        //                 this.ruleForm.service.push(items.value)
        //             } else {
        //                 this.ruleForm.service = []
        //             }
        //         })

        //     })
        // },
        clearTimer() {//清除定时器
            clearInterval(this.timer);
            this.timer = null;
        }
    },
    filters: {
        businessType(val) {
            let obj = ''
            switch (val) {
                case '02':
                    obj = '商超'
                    break;
                case '03':
                    obj = '洗衣'
                    break;
                case '04':
                    obj = '家政'
                    break;
                case '05':
                    obj = '咖吧'
                    break;
            }
            return obj
        }

    },
} 